from typing import Optional
from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from apps.schemas.schemas import UserLoginModel
from apps.deps.RSA import get_key_generator
from apps.services.login import get_public_key, authenticate_user

login_in = APIRouter()


@login_in.get('/getkey')
async def get_key_api(k_generator=Depends(get_key_generator)):
    """
    获取RSA公钥
    """
    try:
        pem_public_key = await get_public_key(k_generator)
        return JSONResponse(
            status_code=200,
            content={
                "status": 200,
                "message": "Get key successful",
                "public_key": pem_public_key
            }
        )
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "status": 500,
                "message": f"Error getting public key: {str(e)}",
                "public_key": None
            }
        )


@login_in.post('/login')
async def login_api(user: UserLoginModel, k_generator=Depends(get_key_generator)):
    """
    用户登录
    """
    try:
        result = await authenticate_user(user.username, user.password, k_generator)
        if result:
            return JSONResponse(
                status_code=200,
                content={
                    "status": 200,
                    "message": "Login successful",
                    "access_token": result["access_token"],
                    "role": result["role"],
                    "userid": result["user_id"]
                }
            )
        else:
            return JSONResponse(
                status_code=401,
                content={
                    "status": 401,
                    "message": "Invalid username or password",
                    "access_token": None,
                    "role": None,
                    "userid": None
                }
            )
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "status": 500,
                "message": f"Error during login: {str(e)}",
                "access_token": None,
                "role": None,
                "userid": None
            }
        )
